<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;
use think\cache\driver\File;

/**
 * vue商城
 *商品单位管理
 * @icon fa fa-user
 */
class Order extends Backend
{
    /**
     * 查看
     */
    protected $relationSearch = true;
    protected $expressqueryModel = null;
    protected $orderPromodel = null;
    protected $BusinessModel= null;
    protected $RecordModel= null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Product.Order.Order');
        $this->expressqueryModel = model('Expressquery');
        $this->BusinessModel = model('Business.Business');
        $this->RecordModel = model('Business.Record');
        $this->orderPromodel = model('Product.Order.Product');
        $status = [
            '0' => '未支付',
            '1' => '已支付',
            '2' => '已发货',
            '3' => '已收货',
            '4' => '已完成',
            '-1' => '仅退款',
            '-2' => '退款退货',
            '-3' => '售后中',
            '-4' => '审核成功',
            '-5' => '审核失败'
        ];
        $this->view->assign('status', $status);
    }
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->with(['expressquery', 'business'])
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->with(['expressquery', 'business'])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    // 发货
    public function deliver($ids = null)
    {
        $expressquery = $this->expressqueryModel->all();
        $data = [];
        foreach ($expressquery as $item) {
            $data[$item['id']] = $item['name'];
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['id'] = $ids;
            $params['shipmanid'] = $this->auth->id;
            $params['status'] = 2;
            // 定义验证器
            $validate = [
                [
                    'expressid' => 'require',
                    'expresscode' => 'require|unique:order'
                ],
                [
                    'expressid.require' => '配送物流未知',
                    'expresscode.unique' => '配送物流单号已存在，请重新输入',
                    'expresscode.require' => '请输入配送物流单号'
                ]
            ];

            $result = $this->model->validate(...$validate)->isUpdate(true)->save($params);
            if ($result === false) {
                $this->error($this->model->getError());
            } else {
                $this->success('发货成功');
            }
        }

        $this->assign('expressquery', $data);
        return $this->view->fetch();
    }
    // 订单详情
    public function info($ids = null)
    {
        $row = $this->model->with(['business', 'region', 'expressquery', 'dispatched'])->find($ids);
        $OrderProductData = $this->orderPromodel->with(['products'])->where('orderid', $ids)->select();
        $this->assign(['row' => $row, 'OrderProductData' => $OrderProductData]);
        return $this->view->fetch();
    }
    // 退货审核
    public function refund($ids = null)
    {
        $row = $this->model->find($ids);

        if ($this->request->isPost()) {
          
            $params = $this->request->post("row/a");
            $orderdata = [
                'id'=>$ids,
                'checkmanid' => $this->auth->id
            ];
            if ($params['refund']) {
                if ($row['status'] == '-1') {
                    $orderdata['status'] = '-4';
                    $money=$row['amount'];
                    $recordData=[
                        'total'=>$money,
                        'content'=>'vue商城的订单号'.$row['code'].'退了'.$money.'元到余额上',
                        'busid'=>$row['busid'],
                        'state'=>'6' 
                    ];
                    
                } elseif ($row['status'] == '-2') {
                    $orderdata['status'] = '-3';
                }
            } else {
                $orderdata['status'] = '-5';
                if(!$params['examinereason']){
                    $this->error("请输入审核失败原因");
                }
                $orderdata['examinereason'] = $params['examinereason'];
            }
            if(isset($money)){
                $bus=$this->BusinessModel->find($row['busid']);
                if(!$bus){
                    $this->error("用户不存在");
                }
                $sum=bcadd($bus['money'],$money,2);
                $this->BusinessModel->startTrans();
                $this->RecordModel->startTrans();
                $this->model->startTrans();
                $busResult=$this->BusinessModel->isUpdate()->save([
                    'id' => $row['busid'],
                    'money'=>$sum
                ]);
                if(!$busResult){
                    $this->error("用户余额更新失败");
                }
                $recordResult=$this->RecordModel->validate('common/Business/Record')->save($recordData);
                if(!$recordResult){
                    $this->BusinessModel->rollback();
                    $this->error($this->RecordModel->getError());
                }
                $result = $this->model->isUpdate()->save($orderdata);
                if (!$result) {
                    $this->BusinessModel->rollback();
                    $this->RecordModel->rollback();
                    $this->error("审核失败");
                }
                $this->BusinessModel->commit();
                $this->RecordModel->commit();
                $this->model->commit();
                $this->success("审核成功");
            }
            $result = $this->model->isUpdate()->save($orderdata);
            if (!$result) {
                $this->error("审核失败");
            }
            $this->success("审核成功");
        }
        $this->assign(['row' => $row]);
        return $this->view->fetch();
    }
     /**
     * 软删除
     */
    public function del($ids = null)
    {
        $categoryList=$this->model->all($ids);
        if(empty($categoryList)){
            $this->error('当前订单不存在');
        }
        $result=$this->model->destroy($ids);
        if(!$result){
            $this->error($this->model->getError());
        }
        $this->success();
    }
}
